package com.inibb.app.service.security.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.inibb.app.service.security.IAuthorityService;
import com.inibb.app.service.security.IRoleService;
import com.inibb.app.service.security.IUserService;
import com.inibb.app.vo.security.AuthorityDTO;
import com.inibb.app.vo.security.RoleDTO;
import com.inibb.app.vo.security.UserVO;




@Component
public class CustomUserDetailService implements UserDetailsService {


	@Autowired
	private IUserService userService;
	@Autowired
	private IRoleService roleService;
	@Autowired
	private IAuthorityService authorityService;

	public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException {
		UserVO user = userService.getUserByLoginName(userName);
		if (user == null)
			throw new UsernameNotFoundException(userName + " Not Found!");

		List<GrantedAuthority> authsList = new ArrayList<GrantedAuthority>();

		for (RoleDTO role : roleService.searchRolesByUserId(user.getId())/*user.getRoles()*/) {
			for (AuthorityDTO authority : authorityService.getRoleAuthorities(role.getId().toString())/*role.getAuths()*/) {
				authsList.add(new GrantedAuthorityImpl(authority.getName()));
			}
		}

		boolean enabled = true;
		if(!"Y".equals(user.getActiveFlag())){
			enabled = false;
		}
		
		// 目前在web的User类中没有enabled, accountNonExpired,credentialsNonExpired, accountNonLocked等属性
		// 暂时全部设为true,在需要时才添加这些属性.
		org.springframework.security.core.userdetails.User userdetail = new org.springframework.security.core.userdetails.User(
				user.getLoginName(), user.getPassword(), enabled, true, true, true, authsList);

		return userdetail;
	}

	@Required
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
}
